package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

/**
 * Created by zw on 2016/4/5 0005.
 */
public class WebViewActivity extends ABBaseActivity {

    private TitleBar titleBar;
    private WebView webView;
    private String content, flag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
//        if ()


        webView = getViewById(R.id.web_view);

        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);

        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        // 加上这句话，支持html5的某些alert提示框的弹出
        webView.getSettings().setDomStorageEnabled(true);

        if (bundle != null) {
            titleBar.setTiteTextView(bundle.getString(Constant.TITLE));
            flag = bundle.getString(Constant.INTENT_FLAG);
            if (Constant.CANPS_QUERY.equals(flag)) {
                // 设置可以支持缩放
                webView.getSettings().setSupportZoom(true);
                // 设置出现缩放工具
//                webView.getSettings().setBuiltInZoomControls(true);
                //扩大比例的缩放
//                webView.getSettings().setUseWideViewPort(true);

                content = bundle.getString(Constant.CANPS_QUERY);
                LogUtils.d("TAG", "content = " + content);
                webView.loadUrl(content);

                //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
                webView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // TODO Auto-generated method stub
                        //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                        view.loadUrl(url);
                        return true;
                    }

                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                        super.onPageStarted(view, url, favicon);
                        showProgressDialog("加载中，请稍等");
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
//                        super.onPageFinished(view, url);
                        dismissProgressDialog();
                    }
                });
//                webView.loadDataWithBaseURL(content, null, "text/html", "UTF-8", null);
            } else if (!TextUtils.isEmpty(flag) && Constant.AGREEMENT.equals(flag)) {
                //盛代宝服务协议
                webView.loadUrl(Constant.URL.AGREEMENT_HTML);
            } else if (Constant.NEWS_CENTER.equals(flag)) {
                String link = bundle.getString(Constant.LINK);
                //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
                webView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // TODO Auto-generated method stub
                        //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                        view.loadUrl(url);
                        return true;
                    }

                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                        super.onPageStarted(view, url, favicon);
                        showProgressDialog("加载中，请稍等");
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
//                        super.onPageFinished(view, url);
                        dismissProgressDialog();
                    }
                });
                if (!TextUtils.isEmpty(link) && URLUtil.isNetworkUrl(link)) {//消息中心分为内容和链接
                    // 设置可以支持缩放
                    webView.getSettings().setSupportZoom(true);
                    // 设置出现缩放工具
//                    webView.getSettings().setBuiltInZoomControls(true);
//                    //扩大比例的缩放
//                    webView.getSettings().setUseWideViewPort(true);
                    webView.loadUrl(link);
                } else {
                    content = SPUtils.getString(Constant.NEWS_CONTENT);
//                    content = bundle.getString(Constant.NEWS_CONTENT);
                    LogUtils.d("TAG", "content = " + content);
                    webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
                }
            }

            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress >= 80) {
                        dismissProgressDialog();
                    }
                }

                @Override
                public void onReceivedIcon(WebView view, Bitmap icon) {

                    super.onReceivedIcon(view, icon);
                }

                @Override
                public void onGeolocationPermissionsShowPrompt(String origin,
                                                               GeolocationPermissions.Callback callback) {

                    callback.invoke(origin, true, false);

                    super.onGeolocationPermissionsShowPrompt(origin, callback);

                }

            });
            webView.setDownloadListener(new MyWebViewDownLoadListener());

        }
    }

    @Override
    protected void eventOnClick() {

    }

    /**
     * @author Administrator
     * @date 2014-7-2
     * @function Android Webview实现文件下载功能
     */
    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        webView.freeMemory();
        webView.clearSslPreferences();
        webView.clearView();
        webView.clearFormData();
        webView.clearHistory();
        webView.clearCache(true);
        webView.clearMatches();
        webView.removeAllViews();
//                    webView.destroy();
        webView.destroy();

        super.onDestroy();
    }

    // 回退键重写
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && webView.canGoBack()) {
            webView.goBack();
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }
}
